package com.homework.hugh.controller;

import com.homework.hugh.cache.GuavaService;
import com.homework.hugh.entity.TokenInfo;
import com.homework.hugh.util.CheckCodeResult;
import com.homework.hugh.util.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @Author: Hugh
 * @Date: 2020/10/26
 */
@RestController
@RequestMapping("/api/user")
public class RegisterController {

    @Autowired
    private GuavaService guavaService;

    /**
     * 注册接⼝
     * @param email 邮箱
     * @param password 密码
     * @param code 验证码
     * @return true成功，false失败
     */
    @GetMapping("/register/{email}/{password}/{code}")
    public String register(@PathVariable String email,
                           @PathVariable String password,
                           @PathVariable String code,
                           HttpServletResponse response){

        //1、先验证token是否有效
        Object o = guavaService.get(Constant.code_key);
        if(Objects.isNull(o)){
            CheckCodeResult.TIMEOUT.msg();
        }
        if(o.toString().equals(code)){
            CheckCodeResult.ERROR.msg();
        }
        //2、然后进行保存
        String token = email + password;
        TokenInfo tokenInfo = TokenInfo.builder()
                .token(token)
                .email(email).build();
        guavaService.save(Constant.token_key_pre + email, tokenInfo);
        //3、处理token
        Cookie cookie = new Cookie("login_token",token);
        cookie.setPath("/");
        response.addCookie(cookie);
        Cookie emailCookie = new Cookie("login_email",email);
        emailCookie.setPath("/");
        response.addCookie(emailCookie);
        return "0";
    }

}
